package org.helgoboss.janana_tray_repository_management

import org.osgi.framework.{BundleActivator, BundleContext}
import org.helgoboss.janana_tray.{JananaTray, JananaTrayAddOn}
import org.osgi.service.obr.{RepositoryAdmin, Repository}
import org.helgoboss.caching_obr.CachingRepositoryAdmin
import java.awt.MenuItem
import java.awt.event.{ActionEvent, ActionListener}
import java.net.URL
import org.helgoboss.osgi_additions._

class JananaTrayRepositoryManagement extends OsgiContext with OsgiLogging with OsgiProvider with OsgiConsumer {
    
    private var repositoryManagementItem: MenuItem = _
    
    whenBundleActive {
        trayAddOn.providesService[JananaTrayAddOn]
    }
    
    val trayAddOn = new JananaTrayAddOn {
        lazy val menuItem = {
            val repositoryManagementListener = new ActionListener {
                def actionPerformed(e: ActionEvent) {
                    repositoryManagementView.show
                }
            }
            
            val tmp = new MenuItem("Repository Management")
            tmp.addActionListener(repositoryManagementListener)
            tmp
        }
    
        def addToJananaTray(tray: JananaTray) {
            tray.getIcon.getPopupMenu.insert(menuItem, 0)
        }

        def removeFromJananaTray(tray: JananaTray) {
            tray.getIcon.getPopupMenu.remove(menuItem)
            repositoryManagementView.dispose
        }
    }
    
    lazy val repositoryManagementView = new RepositoryManagementView {
        def addRepository(repositoryUrlString: String) {
            optionalService[CachingRepositoryAdmin].foreach { admin =>
                admin.addRepository(new URL(repositoryUrlString), Some(updateRepositoryAddingProgress))
            }
        }
        
        def removeRepository(repository: Repository) { 
            optionalService[RepositoryAdmin].foreach { admin =>
                admin.removeRepository(repository.getURL)
            }
        }
        
        def obtainRepositories = {
            optionalService[RepositoryAdmin] match {
                case Some(admin) => admin.listRepositories.toList
                case None => Nil
            }
        }
    }    
}



